package cn.bincker.csustcj.edu.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;

public class EncryptUtils {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    private static final char[] HEX_TABLE = "0123456789abcdef".toCharArray();

    public static String binary2Hex(byte[] data){
        var result = new StringBuilder();
        for (byte datum : data) {
            result.append(HEX_TABLE[(datum >> 4) & 0x0f]);
            result.append(HEX_TABLE[datum & 0x0f]);
        }
        return result.toString();
    }
    public static String encrypt(String hidStudentId) {
        try {
            var cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            var key = new SecretKeySpec("74d46f81-a865-4283-9f9a-e59f332c".getBytes(), "AES");
            var iv = new IvParameterSpec("1234567890000000".getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, key, iv);
            return binary2Hex(cipher.doFinal(hidStudentId.getBytes()));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
                 InvalidAlgorithmParameterException | BadPaddingException | IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        }
    }
    public static String md5(String content){
        try {
            var md = MessageDigest.getInstance("md5");
            return binary2Hex(md.digest(content.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
